package com.example.cloudmaps;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

public class Register extends Activity {
	
	String mUsername = "";
	String mPassword = "";
	
	// UI references.
	private EditText mUserView;
	private EditText mPasswordView;
	private EditText mPasswordView2;
	
	String pass1 = "";
	String pass2 = "";
	static final String EXTRA_MESSAGE="";
	private static final String PHP_REG = "http://softeng.cs.uwosh.edu/students/meyers11/PHPRegister.php";
	public static final String USERNAME="";
	public static final String PASSWORD="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		mUserView = (EditText) findViewById(R.id.editUser);
		
		mPasswordView = (EditText) findViewById(R.id.editPass);
		
		mPasswordView2 = (EditText) findViewById(R.id.editConfirmPass);
		
		
		findViewById(R.id.regBtn).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						
						pass1 = mPasswordView.getText().toString();
						pass2 = mPasswordView2.getText().toString();
						mUsername = mUserView.getText().toString();
						mPassword = mPasswordView.getText().toString();

						View focusView = null;
						boolean cancel = false;
						
						// Check for a valid password.
						if (TextUtils.isEmpty(mPassword)) {
							mPasswordView.setError(getString(R.string.error_field_required));
							focusView = mPasswordView;
							cancel = true;
						} else if (mPassword.length() < 4) {
							mPasswordView.setError(getString(R.string.error_invalid_password));
							focusView = mPasswordView;
							cancel = true;
						}

						// Check for a valid email address.
						if (TextUtils.isEmpty(mUsername)) {
							mUserView.setError(getString(R.string.error_field_required));
							focusView = mUserView;
							cancel = true;
						} else if (mUsername.equals("")) {
							mUserView.setError(getString(R.string.error_field_required));
							focusView = mUserView;
							cancel = true;
						}
						
						if (cancel) {
							// There was an error; don't attempt login and focus the first
							// form field with an error.
							focusView.requestFocus();
						} else if(!pass1.equals(pass2)){
							mPasswordView.setError(getString(R.string.error_field_required));
							focusView = mPasswordView;
							cancel = true;
						}
						else{
							// Show a progress spinner, and kick off a background task to
							// perform the user login attempt.
							new insertLoginInfo().execute();
							System.out.println("reg:" + mUsername + mPassword);
							new UserRegisterTask().execute(mUsername, mPassword, null);
							Register.this.finish();
							Intent myIntent = new Intent(Register.this, MainActivity.class); 
							startActivityForResult(myIntent, 0);
						}
						
					}
		});
		
	}

	
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}
	
	public class UserRegisterTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("username", params[0]));
				n.add(new BasicNameValuePair("password", params[1]));
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_REG);
				
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost, respondHandler);
					success = true;
				}
				catch(Exception e){
					System.out.println("register failed");
				}
			}
			
			return success;
		}

	}
	
	private class insertLoginInfo extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {
			
			MapDataSource cds2 = new MapDataSource(Register.this);
			
			cds2.open();
			
			try {
				cds2.updateUser(mUsername,mPassword);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			cds2.close();
			
			return "";
		}
		
		@Override
		protected void onPostExecute(String whatever) {
			Intent myIntent = new Intent(Register.this, MainActivity.class);
			startActivityForResult(myIntent, 0);
			finish();
		}
		
	}

}
